
import 'dart:async';

import 'package:e_reception_flutter/common_widgets/common_search_bar_widget/common_search_bar_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/check_in_record/record_history/export_excel/export_excel_page.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';

import 'bean/choose_city_list_item_bean.dart';
import 'widgets/choose_city_gps_bar_widget.dart';
import 'widgets/choose_city_tabs_and_pages_widget.dart';

/// 选择城市页面
///
/// @author: zengxiangxi
/// @createTime: 1/9/21 10:34 AM
/// @specialDemand:
class ChooseCityPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "ChooseCityPage";

  final Map<String,ChooseCityListItemBean> selected;

  ///1-3级
  final int subLevel;
  final bool lightTheme;

  const ChooseCityPage({Key key, this.selected, this.subLevel = 2, this.lightTheme})
      : assert(subLevel != null && subLevel >= 1 && subLevel <= 3),
        super(key: key);

  @override
  _ChooseCityPageState createState() => _ChooseCityPageState();

  static Future<Map<String,ChooseCityListItemBean>> navigatorPush(BuildContext context,{int subLevel,Map<String,ChooseCityListItemBean> selected, bool lightTheme}) {

    return RouterUtils.routeForFutureResult<Map<String,ChooseCityListItemBean>>(
      context,
      ChooseCityPage(
        selected: selected,
        subLevel: subLevel,
        lightTheme: lightTheme,
      ),
      routeName: ChooseCityPage.ROUTER,
    );
  }
}

class _ChooseCityPageState extends State<ChooseCityPage> {

  List<Map<String,ChooseCityListItemBean>> listName;

  ValueNotifier<String> cityNameValueNotifier;

  StreamSubscription _streamSubscription;
  @override
  void initState() {
    super.initState();
    listName = List<Map<String,ChooseCityListItemBean>>();
    cityNameValueNotifier = ValueNotifier(null);
    _streamSubscription = VgEventBus.global.on<SearchCityNameListEventMonitor>()?.listen((event) {
      listName = event?.searchCityNameList;
      setState(() {
      });
    });
  }

  @override
  void dispose() {
    cityNameValueNotifier.dispose();
    _streamSubscription?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if(widget?.lightTheme??false){
      return LightAnnotatedRegion(
        child: Scaffold(
          backgroundColor: Colors.white,
          body: toMainColumnWidget(),
        ),
      );
    }
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: toMainColumnWidget(),
    );
  }

  Widget toMainColumnWidget() {
    return Column(
      children: <Widget>[
        _toTopBarWidget(),
        CommonSearchBarWidget(
          hintText: "输入城市名查询",
          onChanged: (String value){
            cityNameValueNotifier?.value = value;
          },
          onSubmitted: (String value){
            cityNameValueNotifier?.value = value;
          },
          bgColor: (widget?.lightTheme??false)?Color(0xFFF1F4F8):null,
          textColor: (widget?.lightTheme??false)?ThemeRepository.getInstance().getCardBgColor_21263C():null,
        ),
        SizedBox(height: 9),
        if((listName?.length ?? 0)!=0 && cityNameValueNotifier?.value!=null && cityNameValueNotifier?.value!="")
        _searchWidget(),
        if(cityNameValueNotifier?.value==null || cityNameValueNotifier?.value=="")
        ChooseCityGpsBarWidget(lightTheme: widget?.lightTheme??false,),
        if(cityNameValueNotifier?.value==null || cityNameValueNotifier?.value=="")
        Expanded(
          child: ChooseCityTabsAndPagesWidget(
            subLevel: widget?.subLevel,
            selected: widget?.selected,
            cityNameValueNotifier: cityNameValueNotifier,
            selectedFunc: (Map<String,ChooseCityListItemBean> map){
              RouterUtils.pop(context,result:map);
            },
            lightTheme: (widget?.lightTheme??false),
          ),
        )
      ],
    );
  }

  Widget _searchWidget(){
   return Expanded(
     child: ListView.separated(
          itemCount: listName?.length ?? 0,
          padding: const EdgeInsets.all(0),
          physics: BouncingScrollPhysics(),
          keyboardDismissBehavior:
          ScrollViewKeyboardDismissBehavior.onDrag,
          itemBuilder: (BuildContext context, int index) {
            return _listItem(index);
          },
          separatorBuilder: (BuildContext context, int index) {
            return SizedBox(
              height: 0,
            );
          }),
   );

  }

  Widget _listItem(int index){
    StringBuffer strName = StringBuffer();
    if(listName[index]["province"]?.sname != null){
      strName?.write(listName[index]["province"]?.sname);
    }
    if(listName[index]["city"]?.sname!=null){
      strName?.write("-");
      strName?.write(listName[index]["city"]?.sname);
    }
    if(listName[index]["district"]?.sname!=null){
      strName?.write("-");
      strName?.write(listName[index]["district"]?.sname);
    }

    return GestureDetector(
      onTap: (){
        RouterUtils.pop(context,result:listName[index]);
      },
      child: Container(
        height: 45,
        color: (widget?.lightTheme??false)?Colors.white:ThemeRepository.getInstance().getCardBgColor_21263C(),
        padding: const EdgeInsets.symmetric(horizontal: 20),
        alignment: Alignment.centerLeft,
        child: AnimatedDefaultTextStyle(
          duration: DEFAULT_ANIM_DURATION,
          style: TextStyle(
              color: (widget?.lightTheme??false)?ThemeRepository.getInstance().getCardBgColor_21263C():ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
              fontSize: 14,
              height: 1.2),
          child: Text(
            "${strName?.toString()}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
          ),
        ),
      ),
    );
  }

  ///TopBar
  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      isShowBack: true,
      title: "所在城市",
      titleColor: (widget?.lightTheme??false)?ThemeRepository.getInstance().getCardBgColor_21263C():const Color(0xFFD0E0F7),
    );
  }
}
